/**
 * Created with IntelliJ IDEA.
 * User: zet
 * Date: 13-4-4
 * Time: 上午1:18
 * To change this template use File | Settings | File Templates.
 */

(function(win, doc){
    var clientW = doc.body.clientWidth,
        mainScroll = new iScroll('scrollWrapper', {
            snap: true,
            momentum: false,
            hScrollbar: false,
            vScrollbar: true,
            onBeforeScrollStart: function (e) {
                var target = e.target;
                while (target.nodeType != 1) target = target.parentNode;

                if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA')
                    e.preventDefault();
            },

            onScrollEnd: function(){
                /*
                if(this.dirY == 0){
                    this.scrollToPage(this.currPageX, 0);
                }
                */
            }
        }),
        wrapper = $('#scrollWrapper').width(clientW),
        theList = $('#theList'),
        liCache = $('#liCache').width(clientW).attr('id', null).remove(),
        priceCache = $('<li><label><input type="radio" name="test"></label></li>'),

        goodsMap = {},
        count = $('#count'),
        totalPrice = $('#totalPrice'),
        commitOrderBtn = $('#commitOrderBtn'),

        insertGoods = function(goodsObj){
            var i,
                temp = liCache.clone(),
                priceTemp = null,
                priceList = temp.find('ul[name=priceList]'),
                radio = null;
            temp.attr('goodsid', goodsObj.id).find('img').attr('src', win.Config.serverRoot + goodsObj.minImagePath);
            temp.find('button[name=buyBtn]').attr('goodsid', goodsObj.id).on('click', addToCart);

            for(i = 0; i < goodsObj.sizes.length; i ++){
                priceTemp = priceCache.clone();
                radio = priceTemp.find('input[type=radio]').attr('name', 'goodsId-' + goodsObj.id).attr('index', i);
                if(i === 0){
                    radio.attr('checked', 'checked');
                }
                priceTemp.find('label').append(goodsObj.sizes[i].type + ' ￥' + goodsObj.sizes[i].price.toFixed(1));
                priceList.append(priceTemp);
            }
            theList.append(temp);
        },

        addToCart = function(){
            var btn = $(this),
                goodsId = btn.attr('goodsid'),
                goods = goodsMap[goodsId],
                li = btn.closest('li'),
                sizeIndex = li.find('input[type=radio]:checked').attr('index'),
                count = li.find('input[type=number]').val();

            for(var i = 0; i < count; i++){
                OrderManager.addGoods(goodsId, sizeIndex);
            }
        },

        OrderManager = {
            orderMap: {},   //key = goodsId + '-' + sizeIndex, value = count
            addGoods: function(goodsId, sizeIndex){
                sizeIndex = typeof sizeIndex === 'undefined' ? 0 : sizeIndex;
                var id = goodsId + '-' + sizeIndex;

                if(this.orderMap[id]){
                    this.orderMap[id] = this.orderMap[id] + 1;
                }
                else {
                    this.orderMap[id] = 1;
                }
                this.refreshAll();
            },

            getCount: function(){
                var goodsId, count, total = 0;
                for(goodsId in this.orderMap){
                    count = this.orderMap[goodsId];
                    total += count;
                }
                return total;
            },

            getTotalPrice: function(){
                var key, keySizeArr, goodsId, sizeIndex, count, goods, total = 0;
                for(key in this.orderMap){
                    keySizeArr = key.split('-');
                    goodsId = keySizeArr[0];
                    sizeIndex = keySizeArr[1];
                    goods = goodsMap[goodsId];
                    count = this.orderMap[key];
                    total += goods.sizes[sizeIndex].price * count;
                }
                return total;
            },

            refreshPrice: function(){
                var total = this.getTotalPrice();
                totalPrice.text(total.toFixed(1));
            },

            refreshCount: function(){
                var total = this.getCount();
                count.text(total);
            },

            refreshAll: function(){
                this.refreshCount();
                this.refreshPrice();
            },

            commit: function(){
                var key, keySizeArr, goodsId, sizeIndex, count, goods, total = 0,

                    goodsIds = new Array(),
                    types = new Array(),
                    counts = new Array(),
                    prices = new Array();

                for(key in this.orderMap){
                    keySizeArr = key.split('-');
                    goodsId = keySizeArr[0];
                    sizeIndex = keySizeArr[1];
                    goods = goodsMap[goodsId];
                    count = this.orderMap[key];
                    total += goods.sizes[sizeIndex].price * count;

                    goodsIds.push(goodsId);
                    types.push(encodeURIComponent(goods.sizes[sizeIndex].type));
                    counts.push(count);
                    prices.push(goods.sizes[sizeIndex].price);
                }

                total = total.toFixed(1);

                var obj = {
                        shopperId : win.Config.shopperId,
                        customId : 1,
                        machineId : win.Config.machineId,
                        totalPrice : total,
                        itemBuyGoodsIds : goodsIds,
                        itemBuyTypes : types,
                        itemBuyCounts : counts,
                        itemBuyPrices : prices
                    },
                    that = this,
                    params = decodeURIComponent($.param(obj, true));
                $.ajax({
                    type: "post",
                    data: params,
                    dataType: 'json',
                    url: win.Config.serverRoot + 'ajax/buyGoods.htm',
                    beforeSend: function(XMLHttpRequest){

                    },
                    success: function(data){
                        that.orderMap = {};
                        if(data.id){
                            //alert(data.orderNum);
                            location.replace('http://api.kuaipai.cn/qr?chs=350x350&chl=' + data.orderNum);
                        }
                    }
                });
            }
        },

        getAllGoods = function(){
            $.ajax({
                url: win.Config.serverRoot + 'ajax/query/queryShopGoods.htm?shopperId=' + win.Config.shopperId,
                dataType: 'json',
                type: 'get',
                success: function(data){
                    var i;
                    theList.hide();
                    for(i = 0; i < data.length; i++){
                        insertGoods(data[i]);
                        goodsMap[data[i].id] = data[i];
                    }
                    theList.width(clientW * data.length).show();
                    mainScroll.refresh();
                },
                fail: function(a, b){
                    console.log(b);
                },
                async: false
            });
        };

    commitOrderBtn.on('click', function(){
        OrderManager.commit();
    });
    getAllGoods();
})(window, document);